package com.njwb.day15.zqzb.pstmt;

import java.sql.*;

public class PreparedStatementDemo02 {
    public static void main(String[] args) {
        //构建连接对象
        Connection connection= null ;
        //命令器
        PreparedStatement pstmt= null ;
        //结果集
        ResultSet rs = null ;
        String username = "zhangsan";
        //sql注入漏洞
        String password = "1231231'  or 1=1";
        //String password = "123456";
        System.out.println(password);
        try {
            //1、加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
            //3、创建命令器
            pstmt = connection.prepareStatement("select user_name,password from tb_login where user_name=? and password=?");
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //4、准备待执行的sql语句
            //String sql = "select user_name,password from tb_login where user_name='"+username+"' and password='"+password+"";
            //String sql = "select user_name,password from tb_login where user_name='123123' and password ='"+password+"";

            //5.执行sql语句,返回结果集对象，并读取结果集
            rs = pstmt.executeQuery();
            if(rs.next()) {
                System.out.println("登录成功");
            }else{
                System.out.println("登录失败");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6、关闭资源 （倒着关闭）
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(pstmt!=null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
